<template>
  <div class="uploadFile">
    <div
      class="dialog animated"
      :class="open? 'fadeIn':'fadeOut'"
      v-show="show"
      :style="{visibility: (visible?'visible':'hidden')}"
    >
      <div class="panel animated" :class="open? 'zoomIn':''">
        <div class="title">
          上传文件
          <div class="close" @click="cancel(1)"></div>
        </div>
        <div>
          <el-form label-width="240px">
            <el-form-item label="上传文件" :rules="[
      { required: true, message: ''}]">
              <input type="file" id="file" hidden multiple />
              <div class="upload_btn" @click="selectFile()">本地文件上传</div>
              <div class="tip">从我的电脑选择文件上传,建议每次最多上传10个文件,zip文件无法上传,请转换成其他格式文件上传</div>
            </el-form-item>
            <el-form-item label="已选文件" v-if="fileList.length >0" style="margin-bottom:0rem;">
              <div class="file-item">
                <el-checkbox v-model="allChecked" @change="allCheck" class="elbox">全部可下载</el-checkbox>
              </div>
            </el-form-item>
            <el-form-item label v-if="fileList.length >0">
              <div class="file-item" v-for="file in fileList">
                <div class="eltag">
                  <el-tag :key="file.name" closable @close="handleClose(file)">{{file.name}}</el-tag>
                </div>
                <el-checkbox v-model="file.checked" class="elbox" @change="itemCheck">可下载</el-checkbox>
              </div>
            </el-form-item>
            <el-form-item label="开放校区" :rules="[
      { required: true, message: ''}]">
              <el-radio-group v-model="selectCampus" @change="radioChange">
                <el-radio :label="1">全部校区</el-radio>
                <el-radio :label="2">指定校区</el-radio>
              </el-radio-group>
              <el-select
                v-if="selectCampus == 2"
                v-model="selectCampusList"
                multiple
                collapse-tags
                filterable
                @change="selectChange"
                placeholder="请选择或筛选校区"
              >
                <el-option
                  v-for="item in campusList"
                  :key="item.campusId"
                  :label="item.name"
                  :value="item.campusId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="btn_div">
          <div class="btn_sure" @click="importFile()">确定上传</div>
          <div class="btn_cancel" @click="cancel(1)">取消上传</div>
        </div>
      </div>
    </div>
    <el-dialog
      title="正在上传 "
      :visible.sync="dialogFormVisible"
      width="56%"
      :modal="false"
      :close-on-click-modal="false"
    >
      <div>
        <table class="table" cellspacing="0">
          <thead class="thead">
            <tr>
              <td style="width: 4rem;">文件名称</td>
              <td style="width: 4rem;">文件大小</td>
              <td style="width: 6rem;">上传进度</td>
            </tr>
          </thead>
          <tbody class="tbody">
            <tr v-for="item in fileList" :key="item.uuid">
              <td>{{item.name}}</td>
              <td>{{(item.size/(1024*1024)).toFixed(2)}}M</td>
              <td>
                <el-progress
                  :text-inside="true"
                  :stroke-width="20"
                  :percentage="item.downloadProgress"
                  :color="item.dowmloadStatus"
                ></el-progress>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
var vm,
  $file,
  user,
  index = 0;
export default {
  data: function() {
    return {
      show: false,
      open: false,
      visible: false,
      selectCampus: 1,
      selectCampusList: [],
      selectCampusNameList: [],
      checked: false,
      dialogFormVisible: false,
      fileList: [],
      uploader: null, //web直传服务
      baseUrl: "", //文件夹路径
      bosInfo: {}, //bos信息
      resourceParentId: "", //父资源id
      campusList: [], //校区列表
      allChecked: true
    };
  },
  methods: {
    /**全部文件点击可下载事件 */
    allCheck(val) {
      for (let i = 0; i < vm.fileList.length; i++) {
        vm.fileList[i].checked = val;
      }
    },
    /**单个文件点击可下载事件 */
    itemCheck(val) {
      if (val) {
        for (let i = 0; i < vm.fileList.length; i++) {
          if (!vm.fileList[i].checked) {
            vm.allChecked = false;
            vm.$forceUpdate();
            return;
          }
          if (i == vm.fileList.length - 1) {
            vm.allChecked = true;
          }
        }
      } else {
        vm.allChecked = false;
      }
      vm.$forceUpdate();
    },
    selectChange(val) {
      console.log(vm.selectCampusList);
      vm.selectCampusNameList = [];
      for (let i = 0; i < vm.selectCampusList.length; i++) {
        for (let y = 0; y < user.campusList.length; y++) {
          if (vm.selectCampusList[i] == user.campusList[y].campusId) {
            vm.selectCampusNameList.push(user.campusList[y].name);
            break;
          }
        }
      }
    },
    init: function(data) {
      vm.show = true;
      setTimeout(function() {
        vm.open = true;
        vm.visible = true;
      }, 11);

      $file.val("");

      //文件在Bos的路径
      vm.baseUrl = data.bosResourceUrl;
      //文件资源ID
      vm.selectCampus = 1;
      vm.resourceParentId = data.resourceParentId;
      let paras = {
        tempAccessKeyId: vm.bosInfo.accessKeyId,
        tempSecretAccessKey: vm.bosInfo.secretAccessKey,
        tempSessionToken: vm.bosInfo.sessionToken
      };
      //获取campus列表
      user = tool.getItem(lsKey.user, true);
      vm.campusList = user.campusList;
      user.campusList.forEach(item => {
        vm.selectCampusList.push(item.campusId);
        vm.selectCampusNameList.push(item.name);
      });
      //校验stsToken
      api.checkValidityOfSTSToken(paras).then(function(data) {
        if (data.resultCode == 2000) {
          //如果token失效，则保存新的token
          if (data.info.validityOfStsToken) {
            data.info.bosStsTokenInfo.minFileSize = vm.bosInfo.minFileSize;
            data.info.bosStsTokenInfo.maxFileSize = vm.bosInfo.maxFileSize;
            vm.bosInfo = data.info.bosStsTokenInfo;
            //保存到缓存
            tool.setItem(lsKey.stsToken, data.info.bosStsTokenInfo, true);
            vm.uploader = null;
          }
          vm.getUpLoader();
        } else {
          vm.$message.error(data.message);
        }
      });
    },
    radioChange(val) {
      vm.selectCampusList = [];
      vm.selectCampusNameList = [];
      if (val == 1) {
        user.campusList.forEach(item => {
          vm.selectCampusList.push(item.campusId);
          vm.selectCampusNameList.push(item.name);
        });
      }
    },
    /**
     * 获取服务
     */
    getUpLoader() {
      vm.uploader = new baidubce.bos.Uploader({
        browse_button: "#file",
        bos_bucket: vm.bosInfo.bucketName, //bucket名
        bos_endpoint: vm.bosInfo.endpoint, //域名
        bos_ak: vm.bosInfo.accessKeyId, //临时ak
        bos_sk: vm.bosInfo.secretAccessKey, //临时sk
        uptoken: vm.bosInfo.sessionToken, //临时token
        max_file_size: "5Gb", //最大上传大小
        bos_multipart_min_size: "500M", //分块上传最小文件大小
        chunk_size: "100M", //分块上传每块上传的大小
        init: {
          PostInit: function() {
            // uploader 初始化完毕之后，调用这个函数
            console.log("uploader 初始化完毕之后");
          },
          Key: function(_, file) {
            console.log("上传之前", file);
            // file.name =

            return vm.baseUrl + file.name;
          },
          FilesAdded: function(_, files) {
            // 当文件被加入到队列里面，调用这个函数
            console.log("文件被加入FilesAdded", files);
          },
          FilesFilter: function(_, files) {
            let filterList = [];
            for (let i = 0; i < files.length; i++) {
              if (files[i].type.indexOf("zip") == -1) {
                filterList.push(files[i]);
              }
            }
            return filterList;
            // 如果需要对加入到队列里面的文件，进行过滤，可以在
            // 这个函数里面实现自己的逻辑
            // 返回值需要是一个数组，里面保留需要添加到队列的文件
          },
          FileUploaded: function(_, file, info) {
            let currentDownFile = {};
            for (let i = 0; i < vm.fileList.length; i++) {
              if (vm.fileList[i].uuid == file.uuid) {
                currentDownFile = vm.fileList[i];
              }
            }
            if (currentDownFile.uuid == undefined) return;
            let objectIds = [];
            let objectNames = [];
            if(vm.selectCampus==1){
              objectIds.push(user.orgId);
              objectNames.push(user.orgName);
            }
            else{
              for (let i = 0; i < vm.selectCampusList.length; i++) {
                objectIds.push(vm.selectCampusList[i]);
                objectNames.push(vm.selectCampusNameList[i]);
              }
            }
            
            var param = new FormData();
            param.append("url", vm.baseUrl + file.name);
            param.append("parentId", vm.resourceParentId);
            param.append("name", file.name);
            param.append("size", file.size / 1024);
            param.append("isDownloadable", file.checked ? 1 : 0);
            param.append("createUserId", user.userId);
            param.append("createUserName", user.nickName);
            param.append("sort", 0);
            param.append("category", 0);
            param.append("objectIds", objectIds);
            param.append("objectNames", objectNames);
            param.append("assignObjectType", vm.selectCampus==1?2:1);//资源对象类型 1-校区,2-机构
            api.downResourceAdd(param).then(function(data) {
              data = data.data;
              if (data.resultCode == 2000) {
                tool.message({
                  showClose: true,
                  message: file.name + "上传成功",
                  type: "success"
                });
                currentDownFile.dowmloadStatus = "#67C23A";
              } else {
                currentDownFile.dowmloadStatus = "#F56C6C";
                vm.$message.error(file.name + data.message);
              }
              vm.$forceUpdate();
              //关闭弹窗
              vm.cancel(2);
            });
          },
          UploadComplete: function() {},
          BeforeUpload: function(_, file) {
            console.log("上传初始化", file);
            console.log(vm.bosInfo.minFileSize, file.size);
            if (vm.bosInfo.minFileSize > file.size) {
              return false;
            }
            let currentDownFile = {};
            for (let i = 0; i < vm.fileList.length; i++) {
              if (vm.fileList[i].uuid == file.uuid) {
                currentDownFile = vm.fileList[i];
              }
            }
            if (currentDownFile.uuid == undefined) return false;
            // if (file.type == "application/zip") {
            //   return false;
            // }

            // 当某个文件开始上传的时候，调用这个函数
            // 如果想组织这个文件的上传，请返回 false
          },
          UploadProgress: function(_, file, progress, event) {
            var re = /([0-9]+\.[0-9]{2})[0-9]*/;
            let bosProgress = Math.round(progress * 100) / 100;
            let currentDownFile = {};
            for (let i = 0; i < vm.fileList.length; i++) {
              if (vm.fileList[i].uuid == file.uuid) {
                currentDownFile = vm.fileList[i];
              }
            }
            currentDownFile.downloadProgress = parseInt(bosProgress * 100);
            vm.$forceUpdate();
            // 文件的上传进度
          },
          NetworkSpeed: function(_, bytes, time, pendings) {
            var speed = bytes / time; // 上传速度
            var leftTime = pendings / speed; // 剩余时间
          },
          UploadPartProgress: function(_, file, progress, event) {
            // 分片上传的时候，单个分片的上传进度
          },
          ChunkUploaded: function(_, file, result) {
            // 分片上传的时候，单个分片上传结束
          },
          Error: function(_, error, file) {
            console.log("上传失败", error);
            let currentDownFile = {};
            for (let i = 0; i < vm.fileList.length; i++) {
              if (vm.fileList[i].uuid == file.uuid) {
                currentDownFile = vm.fileList[i];
              }
            }
            currentDownFile.dowmloadStatus = "#F56C6C";
            // 如果上传的过程中出错了，调用这个函数
            tool.message({
              showClose: true,
              message: "上传失败，请刷新页面再试！",
              type: "error"
            });
            vm.$forceUpdate();
          },
          UploadResume: function(_, file, partList, event) {
            // 断点续传生效时，调用这个函数，partList表示上次中断时，已上传完成的分块列表
          },
          UploadResumeError: function(_, file, error, event) {
            // 尝试进行断点续传失败时，调用这个函数
          }
        }
      });
    },
    importFile: function() {
      if (vm.fileList.length == 0) {
        tool.message({
          message: "请先选择文件",
          type: "warning"
        });
        return;
      }

      vm.dialogFormVisible = true;
      // 这里由于zip文件需要上传到系统后台，所以采用两种方式上传文件,递归的方式上传到后台，bos组件上传到Bos
      //上传到系统后台(递归下载)
      // vm.sendAxios();
      //上传到Bos
      vm.uploader.start();
    },
    sendAxios() {
      if (index >= vm.fileList.length) {
        index = 0;
        vm.cancel(2);
        return;
      } else {
        if (vm.bosInfo.minFileSize > vm.fileList[index].size) {
          tool.message({
            showClose: true,
            message: vm.fileList[index].name + "的文件大小不符合上传条件",
            type: "warning"
          });
          return false;
        }
        if (vm.fileList[index].type.indexOf("zip") != -1) {
          //上传到服务器
          let objectIds = [];
          let objectNames = [];
          for (let i = 0; i < vm.selectCampusList.length; i++) {
            objectIds.push(vm.selectCampusList[i]);
            objectNames.push(vm.selectCampusNameList[i]);
          }
          var param = new FormData();
          param.append("file", vm.fileList[index]);
          param.append("url", vm.baseUrl + vm.fileList[index].name);
          param.append("parentId", vm.resourceParentId);
          param.append("name", vm.fileList[index].name);
          param.append("size", vm.fileList[index].size / 1024);
          param.append("createUserId", user.userId);
          param.append("sorcreateUserNamet", user.nickName);
          param.append("sort", 0);
          param.append("objectIds", objectIds);
          param.append("objectNames", objectNames);
          // param.append("campusId",vm.$store.state.campusId);

          var config = {
            headers: {
              "Content-Type": "multipart/form-data"
            },
            timeout: 2000000,
            onUploadProgress: function(e) {
              //属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
              //如果lengthComputable为false，就获取不到e.total和e.loaded
              if (e.lengthComputable) {
                //已上传的比例
                var rate = e.loaded / e.total;
                if (rate <= 1) {
                  vm.fileList[index].downloadProgress = parseInt(rate * 100);
                  vm.$forceUpdate();
                }
              }
            }
          };
          api.downResourceAdd(param, config).then(function(data) {
            data = data.data;
            if (data.resultCode == 2000) {
              tool.message({
                showClose: true,
                message: vm.fileList[index].name + "上传成功",
                type: "success"
              });
              vm.fileList[index].dowmloadStatus = "#67C23A";
            } else {
              vm.fileList[index].dowmloadStatus = "#F56C6C";
              vm.$message.error(vm.fileList[index].name + data.message);
            }
            index++;
            vm.$forceUpdate();
            vm.sendAxios();
          });
        } else {
          index++;
          vm.sendAxios();
        }
      }
    },
    handleClose(file) {
      var a = this.fileList.indexOf(file);
      this.fileList.splice(this.fileList.indexOf(file), 1);
    },
    selectFile() {
      $file.val("");
      $file.click();
    },
    uploadOk: function() {
      for (let i = 0; i < vm.fileList.length; i++) {
        if (vm.fileList[i].downloadProgress != 100) {
          return false;
        }
      }
      return true;
    },
    /**type 1 用户点击取消  2下载完成取消 */
    cancel: function(type) {
      if (type == 2 && !vm.uploadOk()) return;
      //隐藏弹窗
      vm.open = false;
      vm.fileList = [];
      vm.selectCampus = 1;
      vm.uploader.stop(); //调用 stop 之后，会终止对文件队列的处理。需要注意的是，不是立即停止上传，而是等到当前的文件处理结束（成功/失败）之后，才会停下来。
      setTimeout(function() {
        vm.show = false;
        vm.visible = false;
        vm.dialogFormVisible = false;
        vm.selectCampusList = [];
        vm.$emit("callback");
      }, 500);
    }
  },
  mounted: function() {
    vm = this;
    user = tool.getItem(lsKey.user, true);
    let stsToken = tool.getItem(lsKey.stsToken, true); //百度云信息
    vm.bosInfo = stsToken;
    if (vm.bosInfo && vm.bosInfo != null) {
      vm.getUpLoader();
    } else {
      tool.message({
        showClose: true,
        message: "系统内部出错，请联系管理员",
        type: "error"
      });
    }

    $file = $("#file");
    $file.change(function() {
      var list = $file[0].files;
      console.log(list);
      vm.allChecked = true;
      for (let i = 0; i < list.length; i++) {
        list[i].downloadProgress = 0;
        list[i].dowmloadStatus = "#409EFF";
        list[i].checked = true;
        if (list[i].type.indexOf("zip") == -1) {
          vm.fileList.push(list[i]);
        }
      }
      vm.fileList.forEach((item)=>{
        if(!item.checked){
          vm.allChecked = false;
          return;
        }
      })
    });
  }
};
</script>
<style lang="scss">
.uploadFile {
  .el-dialog__title {
    line-height: 0.28rem;
    font-size: 0.22rem;
    color: #333333;
  }
  .el-dialog {
    border-radius: 0.1rem;
  }
  .el-dialog__headerbtn {
    font-size: 0.28rem;
  }
  .el-form-item__label {
    font-size: 0.16rem;
    color: #666666;
  }
  .el-checkbox__label {
    font-size: 0.16rem;
    color: #666666;
  }
  .el-radio__label {
    font-size: 0.16rem;
  }
  .el-checkbox {
    margin-right: 0.1rem;
  }
  .file-item {
    overflow: hidden;
    .eltag {
      width: 2rem;
      float: left;
      .el-tag {
        font-size: 0.16rem;
        margin-bottom: 0.06rem;
      }
    }
    .elbox {
      float: right;
      width: 2rem;
      margin-right: 2rem;
    }
  }
  .el-form-item {
    margin-bottom: 0.1rem;
  }
  .tip {
    padding-top: 0.04rem;
    padding-left: 0rem;
    color: #999999;
  }
  .upload_btn {
    width: 1.7rem;
    height: 0.38rem;
    line-height: 0.38rem;
    margin-left: 0.2rem;
    font-size: 0.16rem;
    font-weight: bold;
    border-radius: 0.1rem;
    box-shadow: 0 0 0.2rem 0 rgba(56, 133, 248, 0.2);
    padding-left: 0.5rem;
    color: #ffffff;
    cursor: pointer;
    background-color: #3885f8;
    background-repeat: no-repeat;
    background-size: 0.18rem;
    background-position: 0.2rem center;
    background-image: url(../../../assets/img/clue_manage/export.png);
  }
  .upload_btn:hover {
    background-color: rgba(56, 133, 248, 0.8);
  }
  .operate_btn {
    font-size: 0.16rem;
    color: #2e83f6;
    cursor: pointer;
    user-select: none;
  }
}
</style>
<style scoped src="@/style/module/table.css"></style>
<style scoped src="@/style/module/dialog.css"></style>
<style scoped>
</style>